package com.xyh.transaction.controller;

import com.github.pagehelper.PageInfo;
import com.xyh.transaction.entity.User;
import com.xyh.transaction.entity.dto.user.*;
import com.xyh.transaction.entity.vo.GenderVo;
import com.xyh.transaction.entity.vo.ReturnUserVo;
import com.xyh.transaction.entity.vo.StatusVo;
import com.xyh.transaction.response.ResponseResult;
import com.xyh.transaction.service.UserService;
import com.xyh.transaction.utils.MappingUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

@Slf4j
@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // value：可以当作是接口的简称
    //notes：接口的描述
    //tags：可以额外定义接口组，比如这个接口外层已经有@Api(tags = “用户管理”)，将接口划分到了“用户管理”中，但你可以额外的使用tags，例如tags = "角色管理"让角色管理中也有这个接口文档。

    @ApiOperation(value = "登录接口", notes = "输入用户名和密码登录")
    @PostMapping("/login")
    public ResponseResult<ReturnUserVo> login(
            @ApiParam(value = "用户对象", required = true)
            @RequestBody LoginDto loginDto, HttpServletRequest request) {

        log.info("登录ip：{}", request.getRemoteAddr());
        User user = MappingUtil.mapObject(loginDto, User.class);
        ReturnUserVo returnUserVo = userService.login(user);
        return ResponseResult.success("登陆成功！", returnUserVo);
    }

    /**
     * 退出
     *
     * @return {@link ResponseResult}<{@link Void}>
     */
    @ApiOperation(value = "退出接口", notes = "携带token即可退出登录")
    @PostMapping("/logout")
    public ResponseResult<Void> logout() {
        userService.logout();
        return ResponseResult.success("操作成功！", null);
    }

    /**
     * user列表
     *
     * @param userPageDto req page dto
     * @return {@link ResponseResult}<{@link PageInfo}<{@link User}>>
     */
    @ApiOperation(value = "用户列表", notes = "返回所有用户信息")
    @PostMapping("/list")
    @PreAuthorize("hasRole('Admin')")
    public ResponseResult<PageInfo<User>> list(
            @ApiParam(value = "分页参数实体", required = true)
            @RequestBody UserPageDto userPageDto) {
//        Integer pageNum = (Integer) params.get("pageNum");
//        Integer pageSize = (Integer) params.get("pageSize");
//        return userService.list(Integer.valueOf(pageNum),Integer.valueOf(pageSize));
        PageInfo<User> pageInfo = userService.list(userPageDto);
        return ResponseResult.success("操作成功", pageInfo);
    }

    @ApiOperation(value = "新增用户", notes = "添加新的用户")
    @PostMapping("/add")
    public ResponseResult<Void> add(
            @ApiParam(value = "新增用户信息", required = true)
            @RequestBody EditOrAddDto editOrAddDto) {

        userService.register(editOrAddDto);

        return ResponseResult.success("操作成功！", null);
    }

    @ApiOperation(value = "修改用户", notes = "修改传递过来的用户信息")
    @PostMapping("/edit")
    public ResponseResult<Void> edit(
            @ApiParam(value = "修改用户信息实体", required = true)
            @RequestBody EditOrAddDto editOrAddDto) {
        userService.updateUser(editOrAddDto);
        return ResponseResult.success("操作成功！", null);
    }

    @ApiOperation(value = "添加角色", notes = "为用户添加角色")
    @PostMapping("add/role")
    public ResponseResult<Void> addRole(@RequestBody EditOrAddDto editOrAddDto) {
        Integer id = editOrAddDto.getId();
        Set<String> roleNames = editOrAddDto.getRoleNames();
        userService.addUserRole(id, roleNames);
        return ResponseResult.success("操作成功！", null);
    }

    @ApiOperation(value = "修改状态", notes = "修改用户状态")
    @PostMapping("/change")
    public ResponseResult<Void> exchange(
            @ApiParam(value = "用户状态实体", required = true)
            @RequestBody ChangeDto changeDto) {
        userService.changeStatus(changeDto);
        return ResponseResult.success("操作成功！", null);
    }

    @ApiOperation(value = "重置密码", notes = "根据用户id重置密码")
    @PostMapping("rest_password")
    public ResponseResult<Void> restPassword(
            @ApiParam(value = "用户id实体", required = true)
            @RequestBody RestPwdDto restPwdDto) {
        userService.restPassword(restPwdDto);
        return ResponseResult.success("操作成功！", null);
    }

    @ApiOperation(value = "修改密码", notes = "根据id修改密码")
    @PostMapping("set_password")
    public ResponseResult<Void> setPassword(@RequestBody User user) {
        userService.setPassword(user);
        return ResponseResult.success("操作成功！", null);
    }

    @ApiOperation(value = "删除用户", notes = "根据id数组删除用户")
    @PostMapping("delete")
    public ResponseResult<Void> delete(
            @ApiParam(value = "删除用户id数组", required = true)
            @RequestBody ArrDto arrDto) {
        userService.delete(arrDto);
        return ResponseResult.success("操作成功！", null);
    }

    @ApiOperation(value = "导入用户", notes = "导入excel数据")
    @PostMapping("import")
    public ResponseResult<Void> importUser(
            @RequestParam("file") MultipartFile file,
            @RequestParam Map<String, String> params) {
        Boolean isCover = Boolean.valueOf(params.get("isCover"));
        userService.saveUser(file, isCover);
        return ResponseResult.success("操作成功！", null);
    }

    @ApiOperation(value = "导出用户", notes = "导出用户数据为excel")
    @PostMapping("/export")
//    @PreAuthorize("hasRole('Admin')")
    public ResponseEntity<byte[]> export(
            @ApiParam(value = "导出用户筛选条件", required = true)
            @RequestBody ExportDto exportDto) {
        SearchDto searchDto = MappingUtil.mapObject(exportDto, SearchDto.class);
        if (exportDto.getCreateTime() != null) {
            String[] createTime = exportDto.getCreateTime();
            searchDto.setStartTime(createTime[0]);
            searchDto.setEndTime(createTime[1]);
        }

        return userService.exportUserList(searchDto);
    }

    @ApiOperation(value = "性别列表", notes = "返回所有用户性别列表")
    @GetMapping("/gender")
    public ResponseResult<Set<GenderVo>> gender() {

        Set<GenderVo> genderList = userService.getGender();

        return ResponseResult.success("查询成功！", genderList);
    }

    @ApiOperation(value = "状态列表", notes = "返回所有用户状态列表")
    @GetMapping("/status")
    public ResponseResult<Set<StatusVo>> status() {
        Set<StatusVo> statusList = userService.getStatus();
        return ResponseResult.success("查询成功！", statusList);
    }

}
